package com.ljw.vendingmachine.test;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.firefly.api.serialport.SerialPort;
import com.ljw.vendingmachine.MainActivity;
import com.ljw.vendingmachine.R;
import com.ljw.vendingmachine.base.BaseActivity;
import com.ljw.vendingmachine.bean.GoodTest;
import com.ljw.vendingmachine.bean.Goods;
import com.ljw.vendingmachine.bean.MessageEvent;
import com.ljw.vendingmachine.bean.TestItem;
import com.ljw.vendingmachine.utils.ByteUtil;
import com.ljw.vendingmachine.utils.Constant;
import com.ljw.vendingmachine.utils.GsonUtil;
import com.ljw.vendingmachine.utils.LogUtil;
import com.ljw.vendingmachine.utils.ZXingUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.chad.library.adapter.base.BaseQuickAdapter.SCALEIN;
import static com.ljw.vendingmachine.test.Config.PENDING_TEST;

public class GeziTestActivity extends BaseActivity implements SerialPort.Callback {
    @BindView(R.id.rv_goods_test)
    RecyclerView rv_goods_test;
    @BindView(R.id.btn_all_test)
    Button btn_all_test;
    @BindView(R.id.btn_color_reset)
    Button btn_color_reset;
    @BindView(R.id.btn_back)
    Button btn_back;
    private BaseQuickAdapter<TestItem, BaseViewHolder> goods_list_adapter;

    //串口
    private SerialPort mSerialPort = null;


    int index;
    private Runnable runnable;

    @Override
    public int setContentView() {
        return R.layout.activity_gezi_test;
    }


    /**
     * 初始化界面空间
     */
    @Override
    public void initView() {
        rv_goods_test.setLayoutManager(new GridLayoutManager(this, 3));
        goods_list_adapter = new BaseQuickAdapter<TestItem, BaseViewHolder>(R.layout.goods_item_test, null) {
            @Override
            protected void convert(BaseViewHolder helper, TestItem item) {
                if (item.getStatus() == PENDING_TEST) {
                    helper.setText(R.id.tv_goods_test_item, "待测试");
                    helper.setBackgroundColor(R.id.tv_goods_test_item, mContext.getResources().getColor(R.color.color_D0D0D0));
                } else if (item.getStatus() == Config.NORMAL) {
                    helper.setText(R.id.tv_goods_test_item, "正常");
                    helper.setBackgroundColor(R.id.tv_goods_test_item, mContext.getResources().getColor(R.color.colorPrimary));
                } else if (item.getStatus() == Config.MALFUCTION) {
                    helper.setText(R.id.tv_goods_test_item, "故障");
                    helper.setBackgroundColor(R.id.tv_goods_test_item, mContext.getResources().getColor(R.color.colorAccent));

                } else if (item.getStatus() == Config.NOT_CONNETCTED) {
                    helper.setText(R.id.tv_goods_test_item, "缺货");
                    helper.setBackgroundColor(R.id.tv_goods_test_item, mContext.getResources().getColor(R.color.color_F8B551));

                }

            }
        };
        goods_list_adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                index = position;
//                int gNo = goods_list_adapter.getItem(position).getgNo();
////                int gNo = Integer.parseInt(gridNo);
//                int checkNumer = 8 + gNo;
//                String gridNo;
//                if (gNo < 10) gridNo = "0" + gNo;
//                else gridNo = String.valueOf(gNo);
//                String s = ByteUtil.getlast8byte(checkNumer);
//                if (s.length() < 2) s = "0" + s;
//                MessageEvent mes = new MessageEvent();
//                String format = String.format(Constant.SERIAL_COMD, String.format(Constant.SERIAL_PORT_GOODS_OUT, gridNo) + s);
//                mes.setData(format);
//                mes.setCode(Constant.SERIALPORT_GEZI_TEST_CMD);
//                EventBus.getDefault().post(mes);
//                dialog.setMessage("命令执行:" + format);
//                dialog.show();
            }
        });
        //设置加载动画
        goods_list_adapter.openLoadAnimation(SCALEIN);
        rv_goods_test.setAdapter(goods_list_adapter);

        //所有格子测试点击事件。
        btn_all_test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                IS_START_TEST=true;
                MessageEvent mes = new MessageEvent();
                mes.setCode(Constant.SERIALPORT_GEZI_START_TEST_CMD);
                EventBus.getDefault().post(mes);
            }
        });
        //重置按钮的点击事件
        btn_color_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<TestItem> data = goods_list_adapter.getData();
                for (TestItem datum : data) {
                    datum.setStatus(PENDING_TEST);
                }
                goods_list_adapter.notifyDataSetChanged();
            }
        });
        //返回按钮的点击事件
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    Handler handler = new Handler();
    static boolean isPOLL = true;

    /**
     * 初始化数据
     */
    @Override
    public void initData() {

        //1.初始化串口
        initSerialPort();
        //获取待测格子信息
        getAllGoodMsg();


        runnable = new Runnable() {
            @Override
            public void run() {
                if (isPOLL) {
                    if (mSerialPort != null)
                        mSerialPort.sendHexMsg(ByteUtil.hexStr2bytes(Constant.SERIAL_PORT_GOODS_TEST_OUT));
                }
                handler.postDelayed(this, 2000);
            }
        };
        handler.postDelayed(runnable, 1000);//每两秒执行一次runnable.
    }

    /**
     * 获取待测格子数据
     */
    private void getAllGoodMsg() {
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setCode(Constant.SEND_CMD);
        messageEvent.setData(Constant.COMD_GET_ALL_GOODS_MSG);
        EventBus.getDefault().post(messageEvent);

    }

    /**
     * 初始化串口
     */
    private void initSerialPort() {
        if (!openSerialPort(Constant.SERIAL_PORT_PATH, Constant.SERIAL_PORT_BAUDRATE)) {
            dialog.setMessage("正在连接设备");
            dialog.show();
        }
    }


    /**
     * @param path     设备路径
     * @param baudrate 波特率
     * @return 是否打开成功
     */
    private boolean openSerialPort(String path, int baudrate) {
        if (mSerialPort != null) mSerialPort.closeSerialPort();
        mSerialPort = null;
        try {
            mSerialPort = new SerialPort(new File(path), baudrate, 0);
            mSerialPort.setCallback(this);
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LogUtil.d("openSerialPort", "open serialport(" + path + ") error:" + e.toString());
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LogUtil.d("openSerialPort", "open serialport(" + path + ") error:" + e.toString());
            return false;
        }
        return true;

    }


    /**
     * 在SetContentView方法之前注册eventBus
     */
    @Override
    public void afterSetContentView() {
        EventBus.getDefault().register(this);
    }


    StringBuffer stringBuffer = new StringBuffer();

    /**
     * 接收串口数据
     *
     * @param bytes
     * @param i
     */
    public static boolean IS_START_TEST=false;
    @Override
    public void onDataReceived(byte[] bytes, int i) {
        String s = ByteUtil.bytes2HexStr(bytes, 0, i);
        stringBuffer.append(s);
        String s1 = stringBuffer.toString();
        //串口信息处理
        if (s1.startsWith("8A8A") && s1.endsWith("55")) {
            LogUtil.e("收到串口数据:", s1);
            stringBuffer.delete(0, s1.length());
            if (IS_START_TEST){


            String substring = s1.substring(6, 8);
            //空闲状态 开始下一条命令
            if ("8A8A07010002000000000A55".equals(s1)) {
                text_next();
                return;
            }
            if ("01".equals(substring)) {
                String gNo = s1.substring(8, 10);
                String s2 = s1.substring(12, 14);
                String s3 = s1.substring(18, 20);
                if ("02".equals(s2)&&"00".equals(s3)) {
                    ack(gNo);
                    TestItem goodsByGNO = getGoodsByGNO(String.valueOf(Integer.valueOf(gNo, 16)));
                    if (goodsByGNO!=null&&!goodsByGNO.isTest()){
                        MessageEvent event = new MessageEvent();
                        event.setCode(Constant.SEND_CMD);
                        if ("00".equals(s1.substring(16, 18))) {
                            goodsByGNO.setStatus(Config.NORMAL);
                            event.setData(String.format(Constant.COMD_SINGLE_GOODS_TEST, goodsByGNO.getId(), 1));

                        } else {
                            goodsByGNO.setStatus(Config.MALFUCTION);
                            event.setData(String.format(Constant.COMD_SINGLE_GOODS_TEST, goodsByGNO.getId(), 0));
                        }
                        goodsByGNO.setTest(true);
                        EventBus.getDefault().post(event);
                    }
                    text_next();

                    return;
                }

            }
            }
          //  mSerialPort.sendHexMsg(ByteUtil.hexStr2bytes(Constant.SERIAL_PORT_GOODS_TEST_OUT));
        }


    }

    /**
     * 发送消息 测试下一条
     */
    public void text_next(){
        MessageEvent mes = new MessageEvent();
        mes.setCode(Constant.SERIALPORT_GEZI_START_TEST_CMD);
        EventBus.getDefault().post(mes);
    }

    /** 根据测试通道号 获取测试对象
     * @param gNo
     * @return
     */
    public TestItem getGoodsByGNO(String gNo) {
        List<TestItem> data = goods_list_adapter.getData();
        for (TestItem goods : data) {
            int anObject = goods.getgNo();
            try {
                int parseInt = Integer.parseInt(gNo);
                if (parseInt == anObject) {
                    return goods;
                }
            } catch (Exception e) {

            }

        }
        return null;
    }


    /**
     * 逐条发送命令
     */
    public void nextCmd() {
        List<TestItem> data = goods_list_adapter.getData();
        for (TestItem datum : data) {
            if (!datum.isTest()) {
                int gNo = datum.getgNo();
//                int gNo = Integer.parseInt(gridNo);
                int checkNumer = 8 + gNo;
                String gridNo=Integer.toHexString(gNo).toUpperCase();
                if (gridNo.length() < 2) gridNo = "0" + gridNo;
                else gridNo = String.valueOf(gNo);
                String s = ByteUtil.getlast8byte(checkNumer);
                if (s.length() < 2) s = "0" + s;
                MessageEvent mes = new MessageEvent();
                String format = String.format(Constant.SERIAL_COMD, String.format(Constant.SERIAL_PORT_GOODS_OUT, gridNo) + s);
                mes.setData(format);
                mes.setCode(Constant.SERIALPORT_GEZI_TEST_CMD);
                EventBus.getDefault().post(mes);
                break;
            }
        }
    }

    public static void main(String[] args){
//        int gNo = 10;
////                int gNo = Integer.parseInt(gridNo);
//        int checkNumer = 8 + gNo;
//        String gridNo=Integer.toHexString(gNo).toUpperCase();
//        if (gridNo.length() < 2) gridNo = "0" + gridNo;
//        else gridNo = String.valueOf(gNo);
        Integer integer = Integer.valueOf("01", 16);
        System.out.print("校验码："+integer);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveData(MessageEvent event) {
        //.获取所有格子信息
        if (Constant.EVENTBUS_CODE_ALL_GOOD_LIST == event.getCode()) {
            if (dialog != null) dialog.dismiss();
            if (goods_list_adapter != null) {
                //商品列表
                List<TestItem> allGoodMsg = GsonUtil.GsonToList(event.getData().toString(), TestItem[].class);
                goods_list_adapter.replaceData(allGoodMsg);
            }
        }

        //发送串口log
        if (Constant.SERIALPORT_GEZI_TEST_CMD == event.getCode()) {
            String data = (String) event.getData();
            mSerialPort.sendHexMsg(ByteUtil.hexStr2bytes(data));
            LogUtil.e("sendCmd:", data);
        }

        if (Constant.SERIALPORT_GEZI_START_TEST_CMD == event.getCode()) {
            isPOLL=true;
            goods_list_adapter.notifyDataSetChanged();
            nextCmd();

        }


    }


    /**
     * 页面销毁回调
     * 1.解绑eventbus 监听
     * 2.关闭串口
     * 3.销毁提示窗
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
//        if (mSerialPort != null)
//            mSerialPort.closeSerialPort();
        if (dialog != null) dialog.dismiss();
        if (handler != null) handler.removeCallbacks(runnable);
    }

    /**
     * 更新格子状态
     */
    public void updateStatus(String gNo){
        int gNumber = Integer.valueOf(gNo,16);
        int checkNumer = 7 + gNumber;
        String che = ByteUtil.getlast8byte(checkNumer);
        if (che.length() < 2) che = "0" + che;
        String format = String.format("8A8A0303%s01%s55", gNo, che);
        LogUtil.e("出货完成发送确认命令:", format);
    }

    /**
     * 回复串口确认消息
     */
    public void ack(String gNo){
        int gNumber = Integer.valueOf(gNo,16);
        int checkNumer = 7 + gNumber;
        gNo=Integer.toHexString(gNumber);
        if (gNo.length()<2)gNo="0"+gNo;
        String che = ByteUtil.getlast8byte(checkNumer);
        if (che.length() < 2) che = "0" + che;
        String format = String.format("8A8A0303%s01%s55", gNo, che);
        LogUtil.e("回复 ack:","通道号："+gNo+ "命令："+ format);
    }
}
